<?php

namespace app\store\model\dealer;

use app\store\model\User as UserModel;
use app\store\model\Wxapp as WxappModel;
use app\common\model\dealer\Withdraw as WithdrawModel;
use app\common\library\wechat\WxPay;
use app\common\service\Order as OrderService;
use app\common\service\Message as MessageService;
use app\common\enum\dealer\withdraw\ApplyStatus as ApplyStatusEnum;
use app\common\enum\dealer\withdraw\PayType as PayTypeEnum;

/**
 * 分销商提现明细模型
 * Class Withdraw
 * @package app\store\model\dealer
 */
class Withdraw extends WithdrawModel
{
    /**
     * 获取器：申请时间
     * @param $value
     * @return false|string
     */
    public function getAuditTimeAttr($value)
    {
        return $value > 0 ? date('Y-m-d H:i:s', $value) : 0;
    }

    /**
     * 获取器：打款方式
     * @param $value
     * @return mixed
     */
    public function getPayTypeAttr($value)
    {
        return ['text' => PayTypeEnum::data()[$value]['name'], 'value' => $value];
    }

    /**
     * 获取器：申请状态
     * @param $value
     * @return mixed
     */
    public function getApplyStatusAttr($value)
    {
        return ['text' => ApplyStatusEnum::data()[$value]['name'], 'value' => $value];
    }

    /**
     * 获取分销商提现列表
     * @param null $user_id
     * @param int $apply_status
     * @param int $pay_type
     * @param string $search
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($user_id = null, $apply_status = -1, $pay_type = -1, $search = '')
    {
        // 构建查询规则
        $this->alias('withdraw')
            ->with(['user'])
            ->field('withdraw.*, dealer.real_name, dealer.mobile, user.nickName,user.mobile,user.avatarUrl,user.open_id')
            ->join('user', 'user.user_id = withdraw.user_id')
            ->join('dealer_user dealer', 'dealer.user_id = withdraw.user_id')
            ->order(['withdraw.create_time' => 'desc']);
        // 查询条件
        $user_id > 0 && $this->where('withdraw.user_id', '=', $user_id);
        !empty($search) && $this->where('user.nickName|user.open_id', 'like', "%$search%");
        $apply_status > 0 && $this->where('withdraw.apply_status', '=', $apply_status);
        $pay_type > 0 && $this->where('withdraw.pay_type', '=', $pay_type);
        // 获取列表数据
        return $this->paginate(15, false, [
            'query' => \request()->request()
        ]);
    }

    /**
     * 分销商提现审核
     * @param $data
     * @return bool
     */
    public function submit($data)
    {
        if (
            $data['apply_status'] == ApplyStatusEnum::AUDIT_REJECT
            && empty($data['reject_reason'])
        ) {
            $this->error = '请填写驳回原因';
            return false;
        }
        $this->transaction(function () use ($data) {
            // 更新申请记录
            $data['audit_time'] = time();
            $this->allowField(true)->save($data);
            // 提现驳回：解冻分销商资金
            if ($data['apply_status'] == ApplyStatusEnum::AUDIT_REJECT) {
                User::backFreezeMoney($this['user_id'], $this['money']);
            }
            // 发送消息通知
            MessageService::send('dealer.withdraw', [
                'withdraw' => $this,
                'user' => UserModel::detail($this['user_id']),
            ]);
        });
        return true;
    }

    /**
     * 确认已打款
     * @return bool
     */
    public function money()
    {
        $this->transaction(function () {
            // 更新申请状态
            $this->allowField(true)->save([
                'apply_status' => 40,
                'audit_time' => time(),
            ]);
            // 更新分销商累积提现佣金
            User::totalMoney($this['user_id'], $this['money']);
            // 记录分销商资金明细
            Capital::add([
                'user_id' => $this['user_id'],
                'flow_type' => 60,
                'money' => -$this['money'],
                'describe' => '申请提现',
            ]);
        });
        return true;
    }

    /**
     * 分销商提现：微信支付企业付款
     * @return bool
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function wechatPay()
    {
        // 微信用户信息
        $user = $this['user']['user'];
        // 生成付款订单号
        $orderNO = OrderService::createOrderNo();
        // 付款描述
        $desc = '分销商提现付款';
        // 微信支付api：企业付款到零钱
        $wxConfig = WxappModel::getWxappCache();
        $WxPay = new WxPay($wxConfig);
        // 请求付款api
        if ($WxPay->transfers($orderNO, $user['open_id'], $this['amount'], $desc)) {
            // 确认已打款
            $this->money();
            return true;
        }
        return false;
    }


    /**
     * 导出
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function dataExport($query = [])
    {

        header("Content-type:text/html;charset=utf-8");
        $mpName = '提现申请';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getDataExport($query,0, $limit,true);

        $xlsTitle = [
            '用户ID', '微信昵称', 'openID', '提现金额', '服务费', '实际提现额', '提现方式', '审核状态', '申请时间',
            '审核时间'
        ];

        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getDataExport($query,$start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }


    /**
     * 财务管理商品订单导出列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getDataExport($query,$start, $limit,$count = false)
    {

        // 检索查询条件
        !empty($query) && $this->setWhere($query);

        if($count==true){
            // 获取数据列表
            return $this->alias('withdraw')
                ->with(['user'])
                ->field('withdraw.*, dealer.real_name, dealer.mobile, user.nickName, user.avatarUrl,user.open_id')
                ->join('user', 'user.user_id = withdraw.user_id')
                ->join('dealer_user dealer', 'dealer.user_id = withdraw.user_id')
                ->order(['withdraw.create_time' => 'desc'])
                ->count();


        }
        // 获取数据列表

        $list =  $this->alias('withdraw')
            ->with(['user'])
            ->field('withdraw.*, dealer.real_name, dealer.mobile, user.nickName, user.avatarUrl,user.open_id')
            ->join('user', 'user.user_id = withdraw.user_id')
            ->join('dealer_user dealer', 'dealer.user_id = withdraw.user_id')
            ->limit($start,$limit)
            ->order(['withdraw.create_time' => 'desc'])
            ->select();

        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {

            $dataArray[] = [
                '用户ID' => $this->filterValue($order['user_id']),
                '微信昵称' =>  $this->filterValue($order['nickName']),
                'openID' => $this->filterValue($order['open_id']),
                '提现金额' => $this->filterValue($order['money']),
                '服务费' => $this->filterValue($order['service_charge']),
                '实际提现额' => $this->filterValue($order['amount']),
                '提现方式' => $this->filterValue($order['pay_type']['text']),
                '审核状态' => $this->filterValue($order['apply_status']['text']),
                '申请时间' => $this->filterValue($order['create_time']),
                '审核时间' => $this->filterValue($order['audit_time']),

            ];
        }

        return  $dataArray;

    }


    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }

    /**
     * 设置检索查询条件
     * @param $query
     */
    private function setWhere($query)
    {

        if (isset($query['search']) && !empty($query['search'])) {
            $this->where('user.nickName|user.open_id', 'like', '%' . trim($query['search']) . '%');
        }

        if (isset($query['user_id']) && !empty($query['user_id'])) {
            $query['user_id'] > 0 && $this->where('withdraw.user_id', '=', $query['user_id']);
        }
        if (isset($query['apply_status']) && !empty($query['apply_status'])) {
            $query['apply_status'] > 0 && $this->where('withdraw.apply_status', '=', $query['apply_status']);
        }
        if (isset($query['pay_type']) && !empty($query['pay_type'])) {
            $query['pay_type'] > 0 && $this->where('withdraw.pay_type', '=', $query['pay_type']);
        }

    }

}